package cn.edu.njust.epms.controller;

import cn.edu.njust.epms.common.R;
import cn.edu.njust.epms.entity.ModApply;
import cn.edu.njust.epms.entity.User;
import cn.edu.njust.epms.entity.UserDetails;
import cn.edu.njust.epms.service.UserService;
import cn.edu.njust.epms.common.Resp;
import com.baomidou.kaptcha.Kaptcha;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 * 完成用户相关功能的交互（登录、注册、信息修改、密码修改）
 */
@RestController
@RequestMapping
public class UserController {
    @Autowired
    UserService us;
    @Autowired
    private Kaptcha kaptcha;
    @PostMapping("/login")
    public Resp<User> Login(HttpServletRequest request, @RequestParam Map<String,Object> map,@RequestBody User user){
//        System.out.println(user);
//        System.out.println("我在运行");
//        User user = new User();
//        String uName = (String)map.get("uName");
//        String uPw = (String) map.get("uPw");
//        System.out.println(uName);
//        System.out.println(uPw);
//        String code = (String) map.get("code");
//        user.setuPw(uPw);
//        user.setuName(uName);
//        try {
//            kaptcha.validate(code);
//        } catch (Exception e) {
//            if (e instanceof KaptchaIncorrectException) {
//                return Resp.error("验证码不正确");
//            } else if (e instanceof KaptchaNotFoundException) {
//                return Resp.error("验证码未找到");
//            } else if (e instanceof KaptchaTimeoutException) {
//                return Resp.error("验证码过期");
//            } else {
//                return Resp.error("未知错误");
//            }
//        }
        Resp<User> userResp = us.Login(user);
        Integer c = userResp.getCode();
        if(c == 1) {//登陆成功，写入session
            User user1 = userResp.getData();
            request.getSession().setAttribute("user", user1);
        }
        return userResp;
    }

    @PostMapping("/logout")
    public Resp<String> Logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return Resp.success("登出成功！");
    }

    @PostMapping("/reg")
    public Resp<User> Register(@RequestBody User user){
        return us.Register(user);
    }


    @GetMapping("/code")
    public void code() {
        kaptcha.render();
    }

//    @PostMapping("/mod_pwd")
//    public Result<String> modPwd(@RequestBody User u,@RequestParam String pwd){
//        return us.updatePwd(u);
//    }

    /**
     * 修改密码
     * @param user
     * @return
     */
    @PostMapping("/mod_pwd")
    public Resp<String> modInfo(@RequestBody User user){
        Resp<String> resp = us.updatePwd(user);
//        Result<String> result = us.updateInfo(user);
        return resp;
    }

    /**
     * 申请修改
     * @param ma
     * @return
     */
    @PostMapping("/apply_mod")
    public Resp<String> appMod(HttpServletRequest request,@RequestBody ModApply ma){

        User user = (User)request.getSession().getAttribute("user");
        ma.setUid(user.getuId());
        return us.applyMod(ma);
    }

    @PostMapping("/add_ud")
    public Resp<String> addUd(HttpServletRequest request,@RequestBody ModApply ma){
        User user = (User)request.getSession().getAttribute("user");
        ma.setUid(user.getuId());
        return us.addDetails(ma);
    }

    /**
     * 展示申请列表
     * @param request
     * @param r
     * @return
     */
    @PostMapping("/user_mod/list")
    public Resp<PageInfo<ModApply>> selectByCondition(HttpServletRequest request,  @RequestBody R r){
        User user = (User)request.getSession().getAttribute("user");
        if(user.getuSts()!=2){
            r.setuId(user.getuId());
        }
        Integer _pageNo = 1;//默认分页参数
        Integer _size = 5;
        String order="mid";
        if (r.getPageNo() != null) {
            _pageNo = r.getPageNo();
        }
        if (r.getSize() != null) {
            _size = r.getSize();
        }
        if (r.getOrder()!=null && r.getOrder().length()>0) {//没有传入排序，则默认以aId排序
            order = r.getOrder();
        }
        PageHelper.startPage(_pageNo,_size,order);
        Resp<List<ModApply>> resp = us.selectAppByCondition(r);
        PageInfo<ModApply> pageInfo = new PageInfo<>(resp.getData());
        return Resp.success(pageInfo);
    }

    /**
     * 审核
     * @param ma
     * @return
     */
    @PostMapping("/aud_apply")
    public Resp<String> auditApply(HttpServletRequest request,@RequestBody ModApply ma){

        Resp<String> resp = us.audApply(ma);
        return resp;
    }

    @PostMapping("/users")
    public Resp<PageInfo<UserDetails>> selectUserByCondition(HttpServletRequest request,@RequestBody R r){
//        System.out.println(r);
        User user = (User)request.getSession().getAttribute("user");
        if(user.getuSts()!=2){
            r.setuId(user.getuId());
        }
        Integer _pageNo = 1;//默认分页参数
        Integer _size = 5;
        String order="user.uId";
        if (r.getPageNo() != null) {
            _pageNo = r.getPageNo();
        }
        if (r.getSize() != null) {
            _size = r.getSize();
        }
        if (r.getOrder()!=null && r.getOrder().length()>0) {//没有传入排序，则默认以aId排序
            order = r.getOrder();
        }
        PageHelper.startPage(_pageNo,_size,order);
        Resp<List<UserDetails>> listResp = us.selectUserByCondition(r);
        PageInfo<UserDetails> pageInfo = new PageInfo<>(listResp.getData());
        return Resp.success(pageInfo);
    }

    @PostMapping("/users/delete")
    public Resp<String> deleteuDetail(UserDetails ud){
        return us.deleteuDetail(ud);
    }

    @PostMapping("/delete_users")
    public Resp<String> deleteUser(User u){
        return us.deleteUser(u);
    }

    @PostMapping("/user/alldetails")
    public Resp<List<UserDetails>> selectUdByuId(HttpServletRequest request){
        User user = (User)request.getSession().getAttribute("user");
        if(user==null){
            return Resp.error("请先登录！");
        }
        return Resp.success(us.selectUdByuId(user.getuId()));
    }


    @PostMapping("/user/ud")
    public Resp<UserDetails> selectUdByPid(@RequestBody R r){

        if(r.getPid()==null){
            return Resp.error("请输入身份证号！");
        }
        UserDetails ud = us.selectUdByPid(r.getPid());
        if(ud==null)
            return Resp.error("该用户不存在！");
        return Resp.success(ud);
    }
}
